package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;
import biz.util.DateUtil;

import com.rfid.project.model.Inbox;
import com.rfid.project.model.Outbox;
import com.rfid.project.model.PersonWeeklyReport;
import com.rfid.project.service.InboxService;
import com.rfid.project.service.OutboxService;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;

@Controller
public class OutboxController {

	private static final Logger logger = LoggerFactory
			.getLogger(OutboxController.class);

	@Autowired
	private OutboxService outboxService;

	@Autowired
	private InboxService inboxService;

	
	@Autowired
	private PeopleService peopleService;

	@RequestMapping(value = "/outboxmgr")
	public String outboxmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<People> peoples = peopleService.findAll();
		model.addAttribute("peoples", peoples);
		return "outboxmgr";
	}

	@RequestMapping(value = "/queryOutbox")
	public String queryOutbox(
			HttpServletRequest request,
			HttpServletResponse response,

			@RequestParam(value = "messageContent", defaultValue = "") String messageContent,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "sendTimeBegin", defaultValue = "") Date sendTimeBegin,
			@RequestParam(value = "sendTimeEnd", defaultValue = "") Date sendTimeEnd,
			@RequestParam(value = "personId", defaultValue = "-1") Long personId,
			@RequestParam(value = "receiverId", defaultValue = "-1") Long receiverId,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<Outbox> outboxs = outboxService.findAll(personId, receiverId,
				sendTimeBegin, sendTimeEnd, messageContent, status, pageNumber,
				pageSize, sort, order);

		JSONObject object = new JSONObject();
		object.put("total", outboxs.getTotalElements());
		JSONArray models = new JSONArray();
		for (Outbox item : outboxs) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	private void wrapData(Outbox item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("messageContent", item.getMessageContent());
		mod.put("status", item.getStatus());
		mod.put("sendTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getSendTime()));
		People person_1 = item.getPerson();
		if (null != person_1) {
			mod.put("personId", item.getPerson().getId());
			mod.put("personName", item.getPerson().getName());
		} else {
			mod.put("personId", "-1");
			mod.put("personName", "");
		}
		People receiver_1 = item.getReceiver();
		if (null != receiver_1) {
			mod.put("receiverId", item.getReceiver().getId());
			mod.put("receiverName", item.getReceiver().getName());
		} else {
			mod.put("receiverId", "-1");
			mod.put("receiverName", "");
		}
	}

	@RequestMapping(value = "/findOneOutbox")
	public String findOneOutbox(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id,
			Model model){
		Outbox outbox = outboxService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(outbox, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/editOutbox", method = RequestMethod.POST)
	public String editOutboxt(HttpServletRequest request,
			HttpServletResponse response, @Valid Outbox outbox, Model model,
			RedirectAttributes redirectAttributes) {
		outboxService.saveOutbox(outbox);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delOutbox")
	public String delOutbox(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.outboxService.deleteOutbox(id);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/myOutboxmgr")
	public String myOutboxmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<People> peoples = peopleService.findAll();
		model.addAttribute("peoples", peoples);
		return "myOutboxmgr";
	}

	@RequestMapping(value = "/queryMyOutbox")
	public String myQueryOutbox(
			HttpServletRequest request,
			HttpServletResponse response,

			@RequestParam(value = "messageContent", defaultValue = "") String messageContent,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "sendTimeBegin", defaultValue = "") Date sendTimeBegin,
			@RequestParam(value = "sendTimeEnd", defaultValue = "") Date sendTimeEnd,
			@RequestParam(value = "receiverId", defaultValue = "-1") Long receiverId,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		People currentUser = (People)request.getSession().getAttribute("currentUser");
		if(currentUser==null){
			return null;
		}
		
		Page<Outbox> outboxs = outboxService.findAll(currentUser.getId(), receiverId,
				sendTimeBegin, sendTimeEnd, messageContent, status, pageNumber,
				pageSize, sort, order);

		JSONObject object = new JSONObject();
		object.put("total", outboxs.getTotalElements());
		JSONArray models = new JSONArray();
		for (Outbox item : outboxs) {
			JSONObject mod = new JSONObject();

			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}

	@RequestMapping(value = "/editMyOutbox", method = RequestMethod.POST)
	public String editMyOutboxt(HttpServletRequest request,
			HttpServletResponse response, @Valid Outbox outbox, Model model,
			RedirectAttributes redirectAttributes) {
		People currentUser = (People)request.getSession().getAttribute("currentUser");
		if(currentUser==null){
			return null;
		}
		
		//保存发件箱信息
		outbox.setPerson(currentUser);
		outbox.setSendTime(DateUtil.nowDate());
		outbox.setStatus(ProcessStatus.SENDED);
		outboxService.saveOutbox(outbox);
		
		//保存收件箱信息
		Inbox inbox = new Inbox();
		inbox.setMessageContent(outbox.getMessageContent());
		inbox.setPerson(outbox.getReceiver());
		inbox.setSender(outbox.getPerson());
		inbox.setReceiveTime(DateUtil.nowDate());
		inbox.setStatus(ProcessStatus.NEW);
		inboxService.saveInbox(inbox);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delMyOutbox")
	public String delMyOutbox(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.outboxService.deleteOutbox(id);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}


	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat();
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
